package com.ityuhao.bigevent.controller;


//import com.ityuhao.bigevent.pojo.Result;
//
//import com.ityuhao.bigevent.pojo.Result1;
//import com.ityuhao.bigevent.pojo.ResultCodeEnum;
import com.ityuhao.bigevent.pojo.Result;
import com.ityuhao.bigevent.pojo.User;
import com.ityuhao.bigevent.service.UserService;
import com.ityuhao.bigevent.utils.JwtUtil;
import com.ityuhao.bigevent.utils.Md5Util;
import com.ityuhao.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {


    @Autowired
    private UserService userService;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    //注册实现
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {

        //判断用户名是否存在
        User u = userService.findByUsername(username);

        if( u==null){
            userService.register(username,password);
//            return Result.ok(null);
            return Result.success();
        }else {
            //return Result.build(null, ResultCodeEnum.USERNAME_USED);
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
        //判断用户名是否存在
        User loginUser = userService.findByUsername(username);
        if( loginUser==null){
           // return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
            return Result.error("用户名不存在");
        }

        // 判断密码是否正确
        if(!Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
            return Result.error("密码错误");
        }
        // 生成token
        Map<String, Object> claims =new HashMap<>();
        claims.put("id",loginUser.getId());
        claims.put("username",loginUser.getUsername());
        String token = JwtUtil.genToken(claims);
        //将token存入redis中
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token,1, TimeUnit.HOURS );
        //返回token
        //return Result.build(JwtUtil.genToken(claims),ResultCodeEnum.SUCCESS);
        return Result.success(token);
    }

    @GetMapping("/userInfo")
    public Result<User> userinfo(@RequestHeader(name = "Authorization") String token){
        //从请求头中获取token
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");//获取用户名
        Map<String, Object> map = ThreadLocalUtil.get();//从ThreadLocal中获取用户信息
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);//根据用户名查询用户
        return Result.success(user);//返回用户信息
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success("修改成功");
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success("修改成功");
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> map,@RequestHeader("Authorization") String token){
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        Map<String, Object> m = ThreadLocalUtil.get();
        String username = (String) m.get("username");
        User user = userService.findByUsername(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("旧密码错误");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        userService.updatePwd((newPwd));
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success("修改成功");
    }
}
